package net.wanho.service.impl;

import cn.hutool.core.lang.UUID;
import lombok.SneakyThrows;
import net.wanho.service.FileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
public class FileServiceImpl implements FileService {

    @Value("${file.path}")
    private String localFilePath;

    @Value("${file.prefix}")
    private String localFilePrefix;

    @Value("${file.domain}")
    private String domain;


    @SneakyThrows
    @Override
    public String uploadFile(MultipartFile file) {
        // 拼接文件上传路径
        String uploadDir = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        String fileName = file.getOriginalFilename();
        fileName = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."));
        File uploadPath = new File(localFilePath + File.separator + uploadDir + File.separator + fileName);

        // 判断文件目录是否存在，不存在则创建
        if (!uploadPath.getParentFile().exists()) {
            uploadPath.getParentFile().mkdir();
        }

        // 保存文件
        file.transferTo(uploadPath);

        // 拼接文件的访问路径 "http://localhost:3333/warehouse/statics/2024-09-13/664300c3-e21e-4867-a256-bee0d5c74cfe.png"
        String url = domain + localFilePrefix + "/" + uploadDir + "/" + fileName;

        return url;
    }
}